<!--
 * @Descripttion: (PLC配置表/plc_config)
 * @Author: (admin)
 * @Date: (2024-10-08)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>

      <el-form-item :label="$t('device.plcConfigPage.page.productionLineCode')" prop="productionLineCode">
        <!-- <el-input v-model="queryParams.productionLineCode" @keyup.enter="handleQuery"
          :placeholder="$t('device.plcConfigPage.page.productionLineCodeInput')" clearable style="width: 260px" /> -->
        <el-select clearable style="width: 260px" v-model="queryParams.productionLineCode"
          @change="queryParams.workstationCode='';state.options.workstationCodeOptions = state.options.productionLineList.find(item => item.lineCode === $event)?.workStation || []"
          :placeholder="$t('device.plcConfigPage.page.productionLineCodeInput')">
          <el-option v-for="item in options.productionLineOptions" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('device.plcConfigPage.page.workStationCode')" prop="workstationCode">
        <!-- <el-input v-model="queryParams.workstationCode" @keyup.enter="handleQuery"
          :placeholder="$t('device.plcConfigPage.page.workStationCodeInput')" clearable style="width: 260px" /> -->
        <el-select clearable style="width: 260px" v-model="queryParams.workstationCode"
          :placeholder="$t('device.plcConfigPage.page.workStationCodeInput')">
          <el-option v-for="item in options.workstationCodeOptions" :key="item.WorkstationCode" :label="item.WorkstationCode"
            :value="item.WorkstationCode" />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('device.plcConfigPage.page.remark')" prop="remark">
        <el-input v-model="queryParams.remark" @keyup.enter="handleQuery"
          :placeholder="$t('device.plcConfigPage.page.remarkInput')" clearable style="width: 200px" />
      </el-form-item>

      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['device:plcconfig:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
    </el-row>

    <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
      highlight-current-row @sort-change="sortChange">

      <!-- 显示列 -->
      <el-table-column v-for="col in columns.filter(o => o.visible)" :key="col.prop" :prop="col.prop" :label="col.label"
        align="center" :width="col.width || 'auto'" :show-overflow-tooltip="true" />

      <!-- 编辑按钮列 -->
      <el-table-column :label="$t('btn.operate')" width="200" align="center">
        <template #default="scope">
          <el-button type="success" size="small" icon="edit" v-hasPermi="['device:plcconfig:edit']"
            @click="handleUpdate(scope.row)">{{ $t("btn.edit") }}</el-button>
          <el-button type="danger" size="small" icon="delete" v-hasPermi="['device:plcconfig:delete']"
            @click="handleDelete(scope.row)">{{ $t("btn.delete") }}</el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />


    <!-- 添加或修改PLC配置表对话框 -->
    <el-dialog :title="title" :lock-scroll="false" v-model="open">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="180px">
        <el-row :gutter="20">

          <!-- <el-col :lg="12">
            <el-form-item label="Id" prop="id">
              <el-input v-model.number="form.id" placeholder="请输入Id" :disabled="opertype != 1"/>
            </el-form-item>
          </el-col> -->

          <el-col :lg="12">
            <el-form-item :label="$t('device.plcConfigPage.tableColumns.productionLineCode')" prop="productionLineCode"
              required>
              <el-input v-model="form.productionLineCode"
                :placeholder="$t('device.plcConfigPage.formDialog.productionLineCode')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('device.plcConfigPage.tableColumns.workstationCode')" prop="workstationCode"
              required>
              <el-input required v-model="form.workstationCode"
                :placeholder="$t('device.plcConfigPage.formDialog.workstationCode')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('device.plcConfigPage.tableColumns.plcType')" prop="plcType">
              <el-input v-model="form.plcType" :placeholder="$t('device.plcConfigPage.formDialog.plcType')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('device.plcConfigPage.tableColumns.plcAddress')" prop="plcAddress" required>
              <el-input v-model="form.plcAddress" :placeholder="$t('device.plcConfigPage.formDialog.plcAddress')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('device.plcConfigPage.tableColumns.cpuType')" prop="cpuType" required>
              <el-select v-model="form.cpuType" :placeholder="$t('device.plcConfigPage.formDialog.cpuType')">
                <el-option label="1200" value="1200"></el-option>
                <el-option label="1500" value="1500"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :lg="12">
            <el-form-item label="是否启用（软删除）" prop="isEnabled">
              <el-radio-group v-model="form.isEnabled">
                <el-radio v-for="item in options.isEnabledOptions" :key="item.dictValue" :value="item.dictValue">
                  {{item.dictLabel}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="创建时间" prop="creationTime">
              <el-date-picker v-model="form.creationTime" type="datetime" :teleported="false" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="创建人" prop="creatorName">
              <el-input v-model="form.creatorName" placeholder="请输入创建人" />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row>
          <el-col :lg="12">
            <el-form-item :label="$t('device.plcConfigPage.tableColumns.slotNumber')" prop="slotNumber" required>
              <el-input v-model.number="form.slotNumber"
                :placeholder="$t('device.plcConfigPage.formDialog.slotNumber')" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item :label="$t('device.plcConfigPage.tableColumns.rackNumber')" prop="rackNumber" required>
              <el-input v-model.number="form.rackNumber"
                :placeholder="$t('device.plcConfigPage.formDialog.rackNumber')" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label="$t('device.plcConfigPage.tableColumns.remark')">
          <el-input type="textarea" v-model="form.remark"
            :placeholder="$t('device.plcConfigPage.formDialog.remark')"></el-input>
        </el-form-item>

      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="plcconfig">
import {
  listPlcConfig,
  addPlcConfig, delPlcConfig,
  updatePlcConfig, getPlcConfig,
  queryProductionLinePlcInfo
}
  from '@/api/business/plcconfig.js'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  productionLineCode: null,
  workstationCode: null,
  remark: null,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
})
const columns = ref([
  { visible: true, prop: 'id', label: 'Id' },
  { visible: true, prop: 'productionLineCode', label: proxy.$t('device.plcConfigPage.tableColumns.productionLineCode') },
  { visible: true, prop: 'workstationCode', label: proxy.$t('device.plcConfigPage.tableColumns.workstationCode') },
  { visible: true, prop: 'plcType', label: proxy.$t('device.plcConfigPage.tableColumns.plcType') },
  { visible: true, prop: 'plcAddress', label: proxy.$t('device.plcConfigPage.tableColumns.plcAddress') },
  { visible: true, prop: 'cpuType', label: proxy.$t('device.plcConfigPage.tableColumns.cpuType') },
  { visible: true, prop: 'slotNumber', label: proxy.$t('device.plcConfigPage.tableColumns.slotNumber') },
  { visible: true, prop: 'rackNumber', label: proxy.$t('device.plcConfigPage.tableColumns.rackNumber') },
  { visible: true, prop: 'remark', label: proxy.$t('device.plcConfigPage.tableColumns.remark') },
  // { visible: false, prop: 'isEnabled', label: '是否启用（软删除）' },
  // { visible: false, prop: 'creationTime', label: '创建时间' },
  // { visible: false, prop: 'creatorName', label: '创建人' },
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

function getList() {
  loading.value = true
  listPlcConfig(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  form: {},
  rules: {
    // id: [
    //   { required: true, message: "Id不能为空", trigger: "blur", type: "number" },
    // ],
    productionLineCode: [
      { required: true, message: proxy.$t('device.plcConfigPage.formDialogVerify.productionLineCode'), trigger: "blur", type: "string" },
    ],
    workstationCode: [
      { required: true, message: proxy.$t('device.plcConfigPage.formDialogVerify.workstationCode'), trigger: "blur", type: "string" },
    ],
    plcAddress: [
      { required: true, message: proxy.$t('device.plcConfigPage.formDialogVerify.plcAddress'), trigger: "blur", type: "string" },
    ],
    cpuType: [
      { required: true, message: proxy.$t('device.plcConfigPage.formDialogVerify.cpuType'), trigger: "blur", type: "string" },
    ],
    slotNumber: [
      { required: true, message: proxy.$t('device.plcConfigPage.formDialogVerify.slotNumber'), trigger: "blur", type: "number" },
    ],
    rackNumber: [
      { required: true, message: proxy.$t('device.plcConfigPage.formDialogVerify.rackNumber'), trigger: "blur", type: "number" },
    ],
  },
  options: {
    // 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    productionLineList: [],
    // 产线
    productionLineOptions: [],
    // workstation code
    workstationCodeOptions: [],
  }
});

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    id: null,
    productionLineCode: null,
    workstationCode: null,
    plcType: null,
    plcAddress: null,
    cpuType: null,
    slotNumber: null,
    rackNumber: null,
    remark: null,
    isEnabled: null,
    creationTime: null,
    creatorName: null,
  };
  proxy.resetForm("formRef")
}


// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  title.value = proxy.$t('device.plcConfigPage.formDialog.addTitle')
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getPlcConfig(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = proxy.$t('device.plcConfigPage.formDialog.editTitle')
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {

      if (form.value.id != undefined && opertype.value === 2) {
        updatePlcConfig(form.value).then((res) => {
          proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
          open.value = false
          getList()
        })
      } else {
        addPlcConfig(form.value).then((res) => {
          proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.id || ids.value

  proxy
    .$confirm(proxy.$t("common.deleteConfirm",[Ids]), proxy.$t("common.systemTips"), {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delPlcConfig(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess(proxy.$t('common.operateSuccess'))
    })
}

handleQuery()

queryProductionLinePlcInfo().then(res => {
  const { code, data } = res
  if (code == 200) {
    state.options.productionLineList = data;
    state.options.productionLineOptions = data.map(item => ({
      dictLabel: item.lineCode,
      dictValue: item.lineCode
    }));
  }
})
</script>